package com.xiaoxing.gongqiju.mvp.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hss01248.frescopicker.FrescoIniter;
import com.hss01248.photoouter.PhotoCallback;
import com.hss01248.photoouter.PhotoUtil;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.xiaoxing.gongqiju.R;
import com.xiaoxing.gongqiju.R2;
import com.xiaoxing.gongqiju.di.component.DaggerLiaoCheng_GongQiJu_GuiHuanComponent;
import com.xiaoxing.gongqiju.di.module.LiaoCheng_GongQiJu_GuiHuanModule;
import com.xiaoxing.gongqiju.mvp.contract.LiaoCheng_GongQiJu_GuiHuanContract;
import com.xiaoxing.gongqiju.mvp.presenter.LiaoCheng_GongQiJu_GuiHuanPresenter;
import com.xiaoxing.gongqiju.mvp.ui.adapter.LiaoCheng_GongQiJu_GuiHuanAdapter;
import com.xiaoxing.gongqiju.mvp.ui.entity.LiaoCheng_GongQiJu_GuiHuan;
import com.xiaoxing.gongqiju.mvp.ui.entity.RepairGongJu;
import com.xiaoxing.gongqiju.mvp.ui.entity.ReturnGongJu;
import com.xw.repo.XEditText;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.iwf.photopicker.utils.ProxyTools;
import me.jessyan.armscomponent.commonres.utils.BottomDialogUtil;
import com.jess.arms.utils.CProgressDialogUtils;
import me.jessyan.armscomponent.commonres.utils.ToolbarUtils;
import me.jessyan.armscomponent.commonres.view.NiceSpinner;
import me.jessyan.armscomponent.commonres.view.RecycleViewDivider;
import me.jessyan.armscomponent.commonsdk.core.RouterHub;
import me.jessyan.armscomponent.commonsdk.utils.Utils;
import okhttp3.RequestBody;

import static com.jess.arms.utils.Preconditions.checkNotNull;


@Route(path = RouterHub.GONGQIJU_LIAOCHENG_ACTIVITY_LIAO_CHENG_GONG_QI_JU_GUI_HUAN)
public class LiaoCheng_GongQiJu_GuiHuanActivity extends BaseActivity<LiaoCheng_GongQiJu_GuiHuanPresenter> implements LiaoCheng_GongQiJu_GuiHuanContract.View, OnRefreshListener, LiaoCheng_GongQiJu_GuiHuanAdapter.ILiaoCheng_GongQiJu_GuiHuanAdapter {


    private static boolean mIsNeedDemo = true;
    @BindView(R2.id.empty_text)
    TextView empty_text;
    @BindView(R2.id.empty_image)
    ImageView empty_image;

    @BindView(R2.id.empty)
    View mEmptyLayout;
    @BindView(R2.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R2.id.refreshLayout)
    RefreshLayout mRefreshLayout;
    @BindView(R2.id.xet_gong_ju_ming_cheng)
    XEditText xetGongJuMingCheng;
    @BindView(R2.id.xet_na_huo_ren_xing_ming)
    XEditText xetNaHuoRenXingMing;
    @BindView(R2.id.xet_na_huo_ren_dian_hua)
    XEditText xetNaHuoRenDianHua;
    @BindView(R2.id.ns_gui_huan_zhuang_tai)
    NiceSpinner nsGuiHuanZhuangTai;
    private LiaoCheng_GongQiJu_GuiHuanAdapter mAdapter;
    private List<LiaoCheng_GongQiJu_GuiHuan.DataBean> mDataBeanList = new ArrayList<>();
    private String mnsGuiHuanZhuangTaiName;
    private String mnsGuiHuanZhuangTaiId; //1: 借出待归还 2: 检修待归还
    private int mCurrentDialogStyle = com.qmuiteam.qmui.R.style.QMUI_Dialog;
    private String mGuiHuanPic = "";
    private BottomDialogUtil mBottomDialogUtilShare;
    private String mWeiXiuPic = "";

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerLiaoCheng_GongQiJu_GuiHuanComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .liaoCheng_GongQiJu_GuiHuanModule(new LiaoCheng_GongQiJu_GuiHuanModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_liao_cheng__gong_qi_ju__gui_huan; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        ToolbarUtils.initToolbarTitleBack(this, getString(R.string.gong_qi_ju_liao_cheng_activity_liao_cheng__gong_qi_ju__gui_huan));
        PhotoUtil.init(this, new FrescoIniter());

        initRefreshLayout();
        initRecyclerView();
        initEmpty();
        bindGuiHuanLeiXing();

    }

    private void bindGuiHuanLeiXing() {

        ArrayList<String> dataNames = new ArrayList();
        dataNames.add("借出待归还");
        dataNames.add("检修待归还");
        ArrayList<String> dataSids = new ArrayList();
        dataSids.add("1");
        dataSids.add("2");
        nsGuiHuanZhuangTai.attachDataSource(dataNames);
        mnsGuiHuanZhuangTaiName = dataNames.get(0);
        mnsGuiHuanZhuangTaiId = dataSids.get(0);

        nsGuiHuanZhuangTai.addOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mnsGuiHuanZhuangTaiName = dataNames.get(position);
                mnsGuiHuanZhuangTaiId = dataSids.get(position);

            }
        });

    }

    private void initEmpty() {
        empty_image.setImageResource(R.drawable.ic_empty);
        empty_text.setTextColor(Color.parseColor("#D8D8D8"));
        empty_text.setText("暂无数据");
    }

    private void initRecyclerView() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(LiaoCheng_GongQiJu_GuiHuanActivity.this));
        mRecyclerView.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.VERTICAL, 10, Color.parseColor("#EEEEEE")));

        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setAdapter(mAdapter = new LiaoCheng_GongQiJu_GuiHuanAdapter(LiaoCheng_GongQiJu_GuiHuanActivity.this, mDataBeanList, this));

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
            }
        });
    }

    private void initRefreshLayout() {
        mRefreshLayout.setRefreshHeader(new
                ClassicsHeader(this).setSpinnerStyle(SpinnerStyle.FixedBehind).setPrimaryColorId(R.color.public_colorPrimary).setAccentColorId(android.R.color.white));
        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.setEnableRefresh(false);
        mRefreshLayout.autoRefresh();
        mRefreshLayout.setEnableLoadMore(false);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {

        //getLiaoCheng_GongQiJu_GuiHuanList();
        mRefreshLayout.finishRefresh();
        mEmptyLayout.setVisibility(View.GONE);

    }

    @Override
    public void getLiaoCheng_GongQiJu_GuiHuanDataSuccess(LiaoCheng_GongQiJu_GuiHuan entityList) {
//
        if (entityList != null && entityList.getData() != null && entityList.getData().size() > 0) {
            mDataBeanList.clear();
            mDataBeanList.addAll(entityList.getData());
            mAdapter.notifyDataSetChanged();
            mEmptyLayout.setVisibility(View.GONE);
            mRecyclerView.setVisibility(View.VISIBLE);
        } else {
            mEmptyLayout.setVisibility(View.VISIBLE);
            mRecyclerView.setVisibility(View.GONE);
        }

    }

    @Override
    public void returnGongJuDataSuccess(ReturnGongJu entityList) {
        showMessage(entityList.getMessage());
        if (entityList.getCode().equals("200")) {
            mGuiHuanPic = "";
            getLiaoCheng_GongQiJu_GuiHuanList();
        }
    }

    @Override
    public void repairGongJuDataSuccess(RepairGongJu entityList) {
        showMessage(entityList.getMessage());
        if (entityList.getCode().equals("200")) {
            mWeiXiuPic = "";
            getLiaoCheng_GongQiJu_GuiHuanList();
        }
    }

    private void getLiaoCheng_GongQiJu_GuiHuanList() {
        HashMap<String, String> map = new HashMap<>();
        map.put("materialtoolname", getGongJuMingCheng());
        map.put("recevieusername", getNaHuoRenXingMing());
        map.put("receiveusephone", getNaHuoRenDianHua());
        map.put("outstatus", mnsGuiHuanZhuangTaiId);
        mPresenter.getLiaoCheng_GongQiJu_GuiHuanList(map);
    }

    @NotNull
    private String getGongJuMingCheng() {
        return xetGongJuMingCheng.getText().toString().trim();
    }

    @NotNull
    private String getNaHuoRenXingMing() {
        return xetNaHuoRenXingMing.getText().toString().trim();
    }

    @NotNull
    private String getNaHuoRenDianHua() {
        return xetNaHuoRenDianHua.getText().toString().trim();
    }

    @Override
    public void showLoading() {
        CProgressDialogUtils.showProgressDialog(this);
    }

    @Override
    public void hideLoading() {
        CProgressDialogUtils.cancelProgressDialog(this);
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(this, message);

    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @OnClick(R2.id.btn_cha_xun)
    public void onViewClicked() {
        mDataBeanList.clear();
        mAdapter.notifyDataSetChanged();
        mEmptyLayout.setVisibility(View.VISIBLE);
        mRecyclerView.setVisibility(View.GONE);
        getLiaoCheng_GongQiJu_GuiHuanList();
    }


    private void xuanZeGuiHuanTuPian() {
        LinearLayout root = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.sales_client_bottom_dialog_pai_zhao, null);
        Button btn_xiang_ce = root.findViewById(me.iwf.photopicker.R.id.btn_xiang_ce);
        Button ben_xiang_ji = root.findViewById(me.iwf.photopicker.R.id.ben_xiang_ji);
        Button btn_qu_xiao = root.findViewById(me.iwf.photopicker.R.id.btn_qu_xiao);
        btn_qu_xiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBottomDialogUtilShare != null)
                    mBottomDialogUtilShare.dismissDiaolog();
            }
        });
        btn_xiang_ce.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBottomDialogUtilShare != null)
                    mBottomDialogUtilShare.dismissDiaolog();

                PhotoUtil.begin()
                        .setNeedCropWhenOne(false)
                        .setNeedCompress(false)
                        .setMaxSelectCount(1)

                        .start(LiaoCheng_GongQiJu_GuiHuanActivity.this, 33, ProxyTools.getShowMethodInfoProxy(new PhotoCallback() {
                            @Override
                            public void onFail(String msg, Throwable r, int requestCode) {
                            }

                            @Override
                            public void onSuccessSingle(String originalPath, String compressedPath, int requestCode) {
//
                                try {
                                    mGuiHuanPic = ArmsUtils.bitmapToString(compressedPath);
                                    showMessage("选择照片成功，请再点击归还按钮，进行归还操作！");
//                                    Bitmap bitmap = BitmapFactory.decodeFile(compressedPath);
//                                    imgZhaoPian.setImageBitmap(bitmap);
                                } catch (Exception e) {
                                    e.printStackTrace();

                                }
                            }

                            @Override
                            public void onSuccessMulti(List<String> originalPaths, List<String> compressedPaths, int requestCode) {
//                                refresh1(originalPaths);

                            }

                            @Override
                            public void onCancel(int requestCode) {
                            }
                        }));
            }
        });
        ben_xiang_ji.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBottomDialogUtilShare != null)
                    mBottomDialogUtilShare.dismissDiaolog();
                PhotoUtil.statusBarColor = R.color.public_black;
                PhotoUtil.titleBarColor = R.color.public_black;
                PhotoUtil.cropAvatar(true).setCropMuskOvalFalse()
                        .start(LiaoCheng_GongQiJu_GuiHuanActivity.this, 23, ProxyTools.getShowMethodInfoProxy(new PhotoCallback() {
                            @Override
                            public void onFail(String msg, Throwable r, int requestCode) {
                            }

                            @Override
                            public void onSuccessSingle(String originalPath, String compressedPath, int requestCode) {
                                try {
                                    mGuiHuanPic = ArmsUtils.bitmapToString(compressedPath);
                                    showMessage("拍照成功，请再点击归还按钮，进行归还操作！");
//                                    Bitmap bitmap = BitmapFactory.decodeFile(compressedPath);
//                                    imgZhaoPian.setImageBitmap(bitmap);
                                } catch (Exception e) {
                                    e.printStackTrace();

                                }
                            }

                            @Override
                            public void onSuccessMulti(List<String> originalPaths, List<String> compressedPaths, int requestCode) {
                            }

                            @Override
                            public void onCancel(int requestCode) {
                            }
                        }));
            }
        });

        mBottomDialogUtilShare = new BottomDialogUtil(LiaoCheng_GongQiJu_GuiHuanActivity.this, root);
        mBottomDialogUtilShare.showDiaolog();

    }

    private void returnGongJu(LiaoCheng_GongQiJu_GuiHuan.DataBean itemData) {

        String item = "";

//        item += " {\n" +
//                "    \"rid\": " + "" + ",\n" +
//                "    \"mid\": " + itemData.getMid() + ",\n" +
//                "    \"oid\": " + itemData.getOid() + ",\n" +
//                "    \"spid\": " + itemData.getSpid() + ",\n" +
//                "    \"picId\": " + "" + ",\n" +
//                "    \"returnuserid\": " + mSharedPreferencesHelper.getString(BaseConstants.UID) + ",\n" +
//                "    \"ReturnNum\": " + itemData.getOutNum() + ",\n" +
//                "    \"returntime\": \"" + ArmsUtils.getDataTime("yyyy-MM-dd HH:mm:ss") + "\",\n" +
//                "    \"Pictures\": [\n" +
//                "      {\n" +
//                "        \"PictureId\": 0,\n" +
//                "        \"PictureExtension\": \"jpg\",\n" +
//                "        \"Picture\": \"" + mGuiHuanPic + "\"\n" +
//                "      }\n" +
//                "    ]\n" +
//                "  },";


        String jsonData = "[" + ArmsUtils.cutLastString(item) + "]";
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), jsonData);

        mPresenter.returnGongJu(body);
    }

    private void showGuiHuanMessageNegativeDialog(LiaoCheng_GongQiJu_GuiHuan.DataBean item) {
        new QMUIDialog.MessageDialogBuilder(this)
                .setTitle("确认归还")
                .setMessage("是否确认归还？")
                .addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction(0, "确定", QMUIDialogAction.ACTION_PROP_NEGATIVE, new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        returnGongJu(item);
                        dialog.dismiss();
                    }
                })
                .create(mCurrentDialogStyle).show();
    }


    private void showWeiXiuMessageNegativeDialog(LiaoCheng_GongQiJu_GuiHuan.DataBean item) {
        new QMUIDialog.MessageDialogBuilder(this)
                .setTitle("确认维修")
                .setMessage("是否确认维修？")
                .addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction(0, "确定", QMUIDialogAction.ACTION_PROP_NEGATIVE, new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        repairGongJu(item);
                        dialog.dismiss();
                    }
                })
                .create(mCurrentDialogStyle).show();
    }

    private void repairGongJu(LiaoCheng_GongQiJu_GuiHuan.DataBean itemData) {

        String item = "";

//        item += "{\n" +
//                "    \"mrid\": " + "" + ",\n" +
//                "    \"mid\": " + itemData.getMid() + ",\n" +
//                "    \"oid\": " + itemData.getOid() + ",\n" +
//                "    \"remark\": \"" + "" + "\",\n" +
//                "    \"repairtype\": 2,\n" +
//                "    \"repairuserid\": " + mSharedPreferencesHelper.getString(BaseConstants.UID) + ",\n" +
//                "    \"repairstatus\": 0,\n" +
//                "    \"repairtime\": \"" + ArmsUtils.getDataTime("yyyy-MM-dd HH:mm:ss") + "\",\n" +
//                "    \"picId\": 0,\n" +
//                "    \"Num\": " + itemData.getOutNum() + ",\n" +
//                "    \"Pictures\": [\n" +
//                "      {\n" +
//                "        \"PictureId\": 0,\n" +
//                "        \"PictureExtension\": \"jpg\",\n" +
//                "        \"Picture\": \"" + mWeiXiuPic + "\"\n" +
//                "      }\n" +
//                "    ]\n" +
//                "  },";


        String jsonData = "[" + ArmsUtils.cutLastString(item) + " ]";
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), jsonData);

        mPresenter.repairGongJu(body);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode != 0)
            PhotoUtil.onActivityResult(this, requestCode, resultCode, data);
    }

    private void xuanZeWeiXiuTuPian() {
        LinearLayout root = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.sales_client_bottom_dialog_pai_zhao, null);
        Button btn_xiang_ce = root.findViewById(me.iwf.photopicker.R.id.btn_xiang_ce);
        Button ben_xiang_ji = root.findViewById(me.iwf.photopicker.R.id.ben_xiang_ji);
        Button btn_qu_xiao = root.findViewById(me.iwf.photopicker.R.id.btn_qu_xiao);
        btn_qu_xiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBottomDialogUtilShare != null)
                    mBottomDialogUtilShare.dismissDiaolog();
            }
        });
        btn_xiang_ce.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBottomDialogUtilShare != null)
                    mBottomDialogUtilShare.dismissDiaolog();

                PhotoUtil.begin()
                        .setNeedCropWhenOne(false)
                        .setNeedCompress(false)
                        .setMaxSelectCount(1)

                        .start(LiaoCheng_GongQiJu_GuiHuanActivity.this, 33, ProxyTools.getShowMethodInfoProxy(new PhotoCallback() {
                            @Override
                            public void onFail(String msg, Throwable r, int requestCode) {
                            }

                            @Override
                            public void onSuccessSingle(String originalPath, String compressedPath, int requestCode) {
//
                                try {
                                    mWeiXiuPic = ArmsUtils.bitmapToString(compressedPath);
                                    showMessage("选择照片成功，请再点击维修按钮，进行维修操作！");
//                                    Bitmap bitmap = BitmapFactory.decodeFile(compressedPath);
//                                    imgZhaoPian.setImageBitmap(bitmap);
                                } catch (Exception e) {
                                    e.printStackTrace();

                                }
                            }

                            @Override
                            public void onSuccessMulti(List<String> originalPaths, List<String> compressedPaths, int requestCode) {
//                                refresh1(originalPaths);

                            }

                            @Override
                            public void onCancel(int requestCode) {
                            }
                        }));
            }
        });
        ben_xiang_ji.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBottomDialogUtilShare != null)
                    mBottomDialogUtilShare.dismissDiaolog();
                PhotoUtil.statusBarColor = R.color.public_black;
                PhotoUtil.titleBarColor = R.color.public_black;
                PhotoUtil.cropAvatar(true).setCropMuskOvalFalse()
                        .start(LiaoCheng_GongQiJu_GuiHuanActivity.this, 23, ProxyTools.getShowMethodInfoProxy(new PhotoCallback() {
                            @Override
                            public void onFail(String msg, Throwable r, int requestCode) {
                            }

                            @Override
                            public void onSuccessSingle(String originalPath, String compressedPath, int requestCode) {
                                try {
                                    mWeiXiuPic = ArmsUtils.bitmapToString(compressedPath);
                                    showMessage("拍照成功，请再点击维修按钮，进行维修操作！");
//                                    Bitmap bitmap = BitmapFactory.decodeFile(compressedPath);
//                                    imgZhaoPian.setImageBitmap(bitmap);
                                } catch (Exception e) {
                                    e.printStackTrace();

                                }
                            }

                            @Override
                            public void onSuccessMulti(List<String> originalPaths, List<String> compressedPaths, int requestCode) {
                            }

                            @Override
                            public void onCancel(int requestCode) {
                            }
                        }));
            }
        });

        mBottomDialogUtilShare = new BottomDialogUtil(LiaoCheng_GongQiJu_GuiHuanActivity.this, root);
        mBottomDialogUtilShare.showDiaolog();

    }

    @Override
    public void caoZuo(LiaoCheng_GongQiJu_GuiHuan.DataBean item) {
        //1  一物一码  2  一类一码
        Bundle bundle = new Bundle();
        bundle.putString("mtid", item.getMtid());
        bundle.putString("materialCodeMode", item.getMaterialCodeMode());
        Utils.navigation(getContext(), RouterHub.GONGQIJU_LIAOCHENG_ACTIVITY_LIAO_CHENG_GONG_QI_JU_GUI_HUAN_CAO_ZUO, bundle);

    }
}
